//
//  LocalFileServer.m
//  ttkan
//
//  Created by jackcheng on 2017/10/24.
//  Copyright © 2017年 xiangyue. All rights reserved.
//


#import "LocalFileServer.h"
#import <GCDWebServerDataResponse.h>
#import <GCDWebServerFileResponse.h>
#import "DLNAConfig.h"


@interface LocalFileServer ()

@property (nonatomic, strong) GCDWebServer *webServer;

@end

@implementation LocalFileServer

@synthesize webServer = _webServer;

+ (instancetype)shareServer
{
	static LocalFileServer *s;
	
	static dispatch_once_t onceToken;
	
	dispatch_once(&onceToken, ^{
		
		s = [[self alloc] init];
		
	});
	
	return s;
}

- (instancetype)init
{
	self = [super init];
	
	if (self) {
		
//		[GCDWebServer setLogLevel:IS_DEBUGING ? kGCDWebServerLoggingLevel_Debug : kGCDWebServerLoggingLevel_Error];
		
		_webServer = [[GCDWebServer alloc] init];
		
	}
	
	return self;
}

- (void)start
{
	[_webServer removeAllHandlers];
	// 监听来自目录文件资源的请求
	[_webServer addHandlerForMethod:@"GET" path:@"/file" requestClass:[GCDWebServerRequest class] asyncProcessBlock:^(__kindof GCDWebServerRequest *request, GCDWebServerCompletionBlock completionBlock) {
		
		NSString *url = [request.URL.absoluteString stringByRemovingPercentEncoding];
		
		NSRange range = [url rangeOfString:@"/file?"];
		
		NSString *parameterString = [url substringFromIndex:(range.location + range.length)];
		
		if (parameterString == nil || [parameterString isEqualToString:@""])
		{
			completionBlock([GCDWebServerResponse responseWithStatusCode:404]);
			
			return;
		}
		
		NSRange pathRange = [parameterString rangeOfString:@"path="];
		
		NSString *pathString = [parameterString substringFromIndex:(pathRange.location + pathRange.length)];
		
		if (pathString == nil || [pathString isEqualToString:@""])
		{
			completionBlock([GCDWebServerResponse responseWithStatusCode:404]);
			
			return;
		}
		
		NSString *documentPath = NSSearchPathForDirectoriesInDomains( NSLibraryDirectory, NSUserDomainMask, YES)[0];
		
		NSString *fullPath = [NSString stringWithFormat:@"%@%@", documentPath, pathString];
		
		if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath])
		{
			completionBlock([GCDWebServerResponse responseWithStatusCode:404]);
			
			return;
		}
		
		GCDWebServerResponse *response = [GCDWebServerFileResponse responseWithFile:fullPath byteRange:request.byteRange];
		
		completionBlock(response);
		
	}];
	
	[_webServer startWithPort:FILE_SERVER_PORT bonjourName:nil];
	
}

- (void)stop
{
	if (_webServer)
	{
		[_webServer stop];
	}
}

- (BOOL)isRunning
{
	if (!_webServer)
	{
		return NO;
	}
	return [_webServer isRunning];
}

- (NSString *)getUrlFromDocumentPath:(NSString *)path
{
	NSString *documentPath = NSSearchPathForDirectoriesInDomains( NSLibraryDirectory, NSUserDomainMask, YES)[0];
	
	NSString *shortPath = [path stringByReplacingOccurrencesOfString:documentPath withString:@""];
	
	NSString *url = [NSString stringWithFormat:@"%@%@path=%@", _webServer.serverURL, @"file?", shortPath];
	
	return [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

@end
